import axios from "axios";
import { ref } from "vue";
import { cloneDeep } from "lodash-es";
import request from "@/api/request";
export const tempInitTemperatureData = {
  bwlq: {
    bwlq_1: "76.6-98.9",
    bwlq_2: "76.6-98.9",
    bwlq_3: "76.6-98.9",
    bwlq_4: "76.6-98.9",
    bwlq_5: "76.6-98.9",
    bwlq_6: "76.6-98.9",
    bwlq_7: "76.6-98.9",
    bwlq_8: "76.6-98.9",
  },
  bs: {
    bs_1: "76.6-98.9",
    bs_2: "76.6-98.9",
    bs_3: "76.6-98.9",
    bs_4: "76.6-98.9",
    bs_5: "76.6-98.9",
    bs_6: "76.6-98.9",
    bs_7: "76.6-98.9",
    bs_8: "76.6-98.9",
  },
  yr: {
    yr_1: "76.6-98.9",
    yr_2: "76.6-98.9",
    yr_3: "76.6-98.9",
    yr_4: "76.6-98.9",
    yr_5: "76.6-98.9",
    yr_6: "76.6-98.9",
    yr_7: "76.6-98.9",
    yr_8: "76.6-98.9",
  },
  hgpc: {
    hgpc_1: "76.6-98.9",
    hgpc_2: "76.6-98.9",
    hgpc_3: "76.6-98.9",
    hgpc_4: "76.6-98.9",
    hgpc_5: "76.6-98.9",
    hgpc_6: "76.6-98.9",
    hgpc_7: "76.6-98.9",
    hgpc_8: "76.6-98.9",
  },
};
/**
 * 处理WebSocket数据并合并到现有结构
 * @param {Object} currentData 现有数据（如tempInitTemperatureData）
 * @param {Object} wsData WebSocket数据 {Temperature: string, data: Object}
 * @returns {Object} 合并后的新数据
 */
export const mergeTemperatureData = (currentData, wsData) => {
  // 深拷贝避免污染原数据
  const newData = cloneDeep(currentData);
  
  const { Temperature, data } = wsData;

  // 校验设备类型
  if (!["bwlq", "bs", "yr", "hgpc"].includes(Temperature)) {
    console.warn(`未知设备类型: ${Temperature}`);
    return currentData;
  }

  // 合并数据
  newData[Temperature] = Object.entries(data).reduce(
    (acc, [key, value]) => {
      // 校验数据格式（区间字符串 "min-max"）
      if (typeof value === "string" && value.includes("-")) {
        acc[key] = value;
      } else {
        console.warn(`设备 ${Temperature} 的数据格式错误: ${key}=${value}`);
        acc[key] = "76.6-98.9"; // 默认值
      }
      return acc;
    },
    { ...currentData[Temperature] }
  );

  return newData;
};

export const getRandomInRange = (rangeStr, decimals = 1) => {
  if (!rangeStr) {
    // 默认返回带指定小数位数的99.9
    return 99.9.toFixed(decimals);
  }
  
  const [minStr, maxStr] = rangeStr.split("-");
  const min = parseFloat(minStr);
  const max = parseFloat(maxStr);
  
  // 生成随机数
  const random = Math.random() * (max - min) + min;
  // 格式化数字，自动补零
  return random.toFixed(decimals);
};
export const useTemperature = () => {
  const initTemperatureData = ref(tempInitTemperatureData);
  request.get("/index/temperature").then((res) => {
    console.log(
      "%c [ res ]-9",
      "font-size:18px; background:#56d19d; color:#9affe1;",
      res
    );
    initTemperatureData.value = res.data;
    
  });
  return { initTemperatureData };
};
